package cn.xiaozhu.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;


/**
 * @author shkstart
 * @date 2019/8/21 - 13:47
 */
@Configuration
@MapperScan("cn.xiaozhu.dao")
@EnableTransactionManagement
public class DataBaseConfig {


    @Value("${database.user}")
    private String userName;
    @Value("${database.password}")
    private String password;
    @Value("${database.url}")
    private String databaseUrl;
    @Value("${database.driver}")
    private String databaseDriver;

    @Bean
    public DriverManagerDataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, userName, password);
        dataSource.setDriverClassName(databaseDriver);
        return dataSource;
    }
     @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
         SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
         factoryBean.setDataSource(dataSource());
         Resource user = new ClassPathResource("mapper/userMapper.xml");
         Resource file = new ClassPathResource("mapper/fileMapper.xml");
         factoryBean.setMapperLocations(new Resource[]{user, file});
         return factoryBean.getObject();

     }
        @Bean
        public DataSourceTransactionManager transactionManager(){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource());
        return dataSourceTransactionManager;

    }


}
